package com.yx.cloud.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.yx.cloud.Interface.BounceCallBack;
import com.yx.cloud.MyApplication;
import com.yx.cloud.R;
import com.yx.cloud.activity.MusicAlbumDetailActivity;
import com.yx.cloud.activity.MusicPlayingActivity;
import com.yx.cloud.adapter.MusicListAdapter;
import com.yx.cloud.header.NormalBounceHandler;
import com.yx.cloud.product.sdk.tmall.AliGenieSdk;
import com.yx.cloud.product.sdk.tmall.DeviceStatus;
import com.yx.cloud.product.sdk.tmall.MusicInfo;
import com.yx.cloud.product.sdk.tmall.req.CreateMusicListParam;
import com.yx.cloud.product.sdk.tmall.req.GetMusicListCateContentParam;
import com.yx.cloud.product.sdk.tmall.req.GetMusicListParam;
import com.yx.cloud.product.sdk.tmall.req.SearchContentParam;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.view.BounceLayout;
import com.yx.cloud.view.DefaultFooter;
import com.yx.cloud.view.DefaultHeader;
import com.yx.cloud.view.MusicBottomSheetDialog;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import java.util.ArrayList;
import java.util.List;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
public class MusicListFragment extends Fragment implements MusicListAdapter.InnerItemOnclickListener, MusicBottomSheetDialog.MusicListOperation {
    public static final int CATE_TYPE_PLAYING_LIST = 0;//当前播放列表
    public static final int CATE_TYPE_PLAY_LIST_HISTORY = 1;//历史播放列表
    public static final int CATE_TYPE_PLAY_LIST_FAVORITE = 2;//收藏列表
    public static final int CATE_TYPE_SEARCH_SONG = 3;//搜索单曲
    public static final int CATE_TYPE_SEARCH_SINGER = 4;//搜索艺人
    public static final int CATE_TYPE_SEARCH_ALBUM = 5;//搜索专辑
    private RecyclerView mListView;
    private MusicListAdapter musicListAdapter;
    private List<MusicInfo> mMusicList;
    private boolean mIsRefresh;
    private BounceLayout blMusic;
    private FrameLayout fl_message_container;
    private String topicType = "";
    private Long cateId;
    private String contentType;
    private LinearLayout llNoMusic;
    private int limit = 100;
    private String playStatus = "";
    private DeviceStatus deviceStatus;
    private String searchContent = "";

    public MusicListFragment(long cateId,String contentType) {
        this.cateId = cateId;
        this.contentType = contentType;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.music_list_fragment, container, false);
        initView(view);
        EventBus.getDefault().register(this);
        new Thread(() -> {
            getPlayingList(1,limit,true);
        }).start();
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_GET_DEVICE_STATUS_DETAIL:
                if (event.isResult()) {
                    Log.d("music","get device status detail success");
                    DeviceStatus deviceStatus = (DeviceStatus) event.getContent();
                    playStatus = deviceStatus.getMusicInfo().getMusicPlayStatus();
                }
                break;
            case Event.MESSAGE_TYPE_GET_CURRENT_PLAYING_ITEM:
                if (event.isResult()) {
                    Log.d("music","get Playing item success");
                    if(cateId == CATE_TYPE_PLAYING_LIST){
                        MusicInfo musicInfo = (MusicInfo) event.getContent();
                        if(musicInfo != null && musicListAdapter.getmMusicInfoList().size() > 0){
                            int playingPos = musicInfo.getPos();
                            if(musicInfo.getRawId().equals(musicListAdapter.getmMusicInfoList().get(playingPos).getRawId())){
                                if(playStatus.equals("play")){
                                    musicListAdapter.getmMusicInfoList().get(playingPos).setMusicPlayStatus("play");
                                    musicListAdapter.selectItem(playingPos);
                                }
                            }
                        }
                    }
                }else {
                    Log.d("music","get Playing item fail");
                    String message = (String)event.getContent();
                    ToastUtil.show(getActivity(), message, Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_MUSIC_PLAY_SWITCH:
                Log.d("music","set music playing");
                int id = (int)event.getContent();
                musicListAdapter.selectItem(id);
                break;
            case Event.MESSAGE_TYPE_SEARCH_CONTENT:
            case Event.MESSAGE_TYPE_LIST_PLAY_HISTORY:
            case Event.MESSAGE_TYPE_GET_CURRENT_PLAYING_LIST:
                if(event.isResult()){
                    GetMusicListParam getMusicListParam = (GetMusicListParam) event.getExtra();
                    if(cateId == getMusicListParam.getCateId()){
                        onDataUpdate(event);
                        Log.d("music","update music list");
                    }
                }else {
                    String message = (String)event.getContent();
                    Log.d("music","return result is not 200，message is " + message);
                    ToastUtil.show(getActivity(), message, Toast.LENGTH_SHORT);
                    if (mIsRefresh) {
                        blMusic.setRefreshCompleted();
                    } else {
                        blMusic.setLoadingMoreCompleted();
                    }
                }
                break;
            case Event.MESSAGE_TYPE_INDEX_PLAY_MUSIC:
                if(event.isResult()){
                    musicListAdapter.notifyDataSetChanged();
                }else {
                    String message = (String)event.getContent();
                    ToastUtil.show(getActivity(), message, Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_GET_CONTENT:
                if(event.isResult()){
                    if(cateId == CATE_TYPE_PLAY_LIST_HISTORY || cateId ==CATE_TYPE_SEARCH_SONG){
                        MusicInfo musicInfo1 = (MusicInfo) event.getContent();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                createPlayListByMusicInfo(musicInfo1);
                            }
                        }).start();
                    }
                }else {
                    String message = (String)event.getContent();
                    ToastUtil.show(getActivity(), message, Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_CREATE_MUSIC_LIST:
                if(event.isResult()){
                    if(cateId == CATE_TYPE_PLAY_LIST_HISTORY || cateId == CATE_TYPE_SEARCH_SONG){
                        Intent intent = new Intent(getActivity(), MusicPlayingActivity.class);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.enteralpha,
                                R.anim.default_anim);
                    }
                }else {
                    ToastUtil.show(getActivity(), event.getContent().toString(), Toast.LENGTH_SHORT);
                }
                break;
        }
    }

    private void initView(View view) {
        llNoMusic = view.findViewById(R.id.ll_noMusic);
        //设置线性布局管理器类型
        mListView = view.findViewById(R.id.music_ListView);
        //设置线性布局管理器类型
        mListView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
        mMusicList = new ArrayList<>();
        musicListAdapter = new MusicListAdapter(getContext(), mMusicList,cateId);
        musicListAdapter.setOnInnerItemOnClickListener(this);
        mListView.setAdapter(musicListAdapter);


        blMusic = view.findViewById(R.id.bl_music_list);

        blMusic.setBounceHandler(new NormalBounceHandler(), mListView);//设置滚动冲突的控制类
        //自定义事件分发处理
        blMusic.setEventForwardingHelper((downX, downY, moveX, moveY) -> true);

        fl_message_container = view.findViewById(R.id.fl_music_list_fragment);
        blMusic.setHeaderView(new DefaultHeader(getContext()), fl_message_container);//设置刷新头，null意味着没有刷新头，不调用该函数意为着空
        blMusic.setFooterView(new DefaultFooter(getContext()), fl_message_container);
        blMusic.setBounceCallBack(new BounceCallBack() {
            @Override
            public void startRefresh() {
                Log.d("music","startRefresh");
                new Thread(() -> {
                    getPlayingList(1,limit,true);
                }).start();
            }

            @Override
            public void startLoadingMore() {
                Log.d("music","startLoadingMore");
                if(musicListAdapter.getItemCount() < limit && musicListAdapter.getItemCount() > 0){
                    GetMusicListParam param = new GetMusicListParam();
                    param.setCateId(cateId);
                    mIsRefresh = false;
                    Event.newBuilder().type(Event.MESSAGE_TYPE_GET_CURRENT_PLAYING_LIST).result(true).extra(param).content(null).send();
                }else {
                    new Thread(() -> {
                        getPlayingList(musicListAdapter.getItemCount() / limit + 1, limit, false);
                    }).start();
                }
                Log.d("music","startLoadingMore");
            }
        });
    }

    public void searchContent(String queryString,int offset, int limit, final boolean isRefresh){
        Log.d("music", " 消息: =======searchContent======== :" + isRefresh + "topicType " + topicType);
        mIsRefresh = isRefresh;
        mMusicList = new ArrayList<>();
        musicListAdapter.clearData();
        searchContent = queryString;
        SearchContentParam searchContentParam = new SearchContentParam();
        searchContentParam.setQuery(queryString);
        searchContentParam.setPageSize(limit);
        searchContentParam.setPageNum(offset);
        searchContentParam.setCateId(cateId);
        if(cateId == CATE_TYPE_SEARCH_SONG){
            searchContentParam.setCate("music");
            searchContentParam.setSubCate("song");
            searchContentParam.setAlbum(false);
        }else if(cateId == CATE_TYPE_SEARCH_SINGER){
            searchContentParam.setCate("music");
            searchContentParam.setSubCate("singer");
            searchContentParam.setAlbum(false);
        }else if(cateId == CATE_TYPE_SEARCH_ALBUM){
            searchContentParam.setCate("music");
            searchContentParam.setSubCate("album");
            searchContentParam.setAlbum(true);
        }
        AliGenieSdk.get().searchContent(searchContentParam);
    }

    private void getPlayingList(int offset, int limit, final boolean isRefresh){
        mIsRefresh = isRefresh;
        mMusicList = new ArrayList<>();
        GetMusicListParam param = new GetMusicListParam();
        param.setPageNum(offset);
        param.setPageSize(limit);
        param.setCateId(cateId);
        if (cateId == CATE_TYPE_PLAYING_LIST) {
            Log.d("music", " 消息: =======getPlayingList======== :" + isRefresh + "topicType " + topicType);
            AliGenieSdk.get().getPlayingList(param);
        } else if (cateId == CATE_TYPE_PLAY_LIST_HISTORY) {
            Log.d("music", " 消息: =======listPlayHistory======== :" + isRefresh + "topicType " + topicType);
            param.setType("music");
            AliGenieSdk.get().listPlayHistory(param);
        }else if(cateId == CATE_TYPE_SEARCH_SONG || cateId == CATE_TYPE_SEARCH_ALBUM){
            if(!searchContent.equals("")){
                searchContent(searchContent,offset,limit,isRefresh);
            }
        }
    }

    private void getMusicList(int offset, int limit, final boolean isRefresh){
        Log.d("music"," 消息: =======getMusicList======== :" + isRefresh + "topicType " + topicType);
        mIsRefresh = isRefresh;
        mMusicList = new ArrayList<>();
        GetMusicListParam param = new GetMusicListParam();
        param.setPageNum(offset);
        param.setPageSize(limit);
        param.setTopicType(topicType);
        //new Thread(() -> AliGenieSdk.get().getMusicListByTopicId(param)).start();
    }

    private void getMusicListCateContent(int pageNum, int pageSize, final boolean isRefresh){
        Log.d("music"," 消息: =======getMusicList======== :" + isRefresh + "topicType = " + topicType + "pageNum =" + pageNum + "pageSize = " + pageSize );
        mIsRefresh = isRefresh;
        mMusicList = new ArrayList<>();
        GetMusicListCateContentParam param = new GetMusicListCateContentParam();
        param.setPageNum(pageNum);
        param.setPageSize(pageSize);
        param.setCateId(cateId);
        param.setAlbum(true);
        AliGenieSdk.get().getMusicListCateContent(param);
    }

    private void getListRecommendContent(int count,final boolean isRefresh){
        Log.d("music"," 消息: =======getMusicList======== :" + isRefresh + "topicType = " + topicType + "count" + count);
        mIsRefresh = isRefresh;
        mMusicList = new ArrayList<>();
        GetMusicListCateContentParam param = new GetMusicListCateContentParam();
        param.setPageSize(count);
        param.setCateId(cateId);
        AliGenieSdk.get().getListRecommendContent(param);
    }

    @Override
    public void itemClick(View v, int position) {
        Log.d("music","itemClick");
        if(cateId == CATE_TYPE_SEARCH_ALBUM) {
            new Thread(() -> {
                Intent intent = new Intent(getActivity(), MusicAlbumDetailActivity.class);
                MusicInfo musicInfo = musicListAdapter.getItem(position);
                musicInfo.setRawId("Search");
                intent.putExtra("musicInfo", new Gson().toJson(musicInfo));
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.in_from_right,
                        R.anim.out_to_left);
            }).start();
        }else if(cateId == CATE_TYPE_PLAY_LIST_HISTORY || cateId == CATE_TYPE_SEARCH_SONG){
            new Thread(() -> {
                MusicInfo musicInfo = musicListAdapter.getItem(position);
                getContentById(musicInfo.getId());
            }).start();
        }else {
            new Thread(() -> {
                indexControlPlay(position);
            }).start();
        }
    }

    @Override
    public void createPlayList(int index) {
        CreateMusicListParam param = new CreateMusicListParam();
        param.setContentType(contentType);
        param.setPlayIndex(index);
        //列表循环：Repeat；随机：Shuffle；单曲循环：RepeatOne；顺序播放：Normal。
        param.setPlayMode("Normal");
        List<MusicInfo> createList = new ArrayList<>();
        if(cateId == CATE_TYPE_SEARCH_SONG){
            param.setContentType("content");
            createList.add(musicListAdapter.getmMusicInfoList().get(index));
            param.setPlayIndex(0);
        }else {
            createList.addAll(musicListAdapter.getmMusicInfoList());
        }
        AliGenieSdk.get().createMusicList(createList, param);
    }

    public void createPlayListByMusicInfo(MusicInfo musicInfo){
        CreateMusicListParam param = new CreateMusicListParam();
        param.setContentType("content");
        param.setPlayIndex(0);
        //列表循环：Repeat；随机：Shuffle；单曲循环：RepeatOne；顺序播放：Normal。
        param.setPlayMode("Normal");
        List<MusicInfo> createList = new ArrayList<>();
        if(cateId == CATE_TYPE_PLAY_LIST_HISTORY || cateId == CATE_TYPE_SEARCH_SONG){
            param.setContentType("content");
            createList.add(musicInfo);
            param.setPlayIndex(0);
        }
        AliGenieSdk.get().createMusicList(createList, param);
    }


    public void indexControlPlay(int index){
        AliGenieSdk.get().indexControlPlay(index);
    }

    public void getContentById(long id){
        AliGenieSdk.get().getContent(id);
    }

    @Override
    public void play() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void next() {

    }

    @Override
    public void previous() {

    }

    @Override
    public void updateData() {

    }

    @Override
    public List<MusicInfo> getMusicInfoList() {
        return null;
    }

    @Override
    public void onDataUpdate(Event event) {
        if (event.isResult()) {
            List<MusicInfo> result = (List<MusicInfo>) event.getContent();
            Log.d("music","parse music list");
            parseMusicInfo(result, mIsRefresh);
        } else {
            llNoMusic.setVisibility(View.VISIBLE);
        }
    }

    private void parseMusicInfo(List<MusicInfo> result, boolean isRefresh) {
        List<MusicInfo> tempList = result;
        LogUtils.i("getMusicInfoList contentType is--> : " +contentType);
        if(tempList != null){
            if (isRefresh) {
                if(cateId == CATE_TYPE_PLAYING_LIST){
                    deviceStatus = AliGenieSdk.get().getCurrentMusic();
                    int playingPos = deviceStatus.getMusicInfo().getPos();
                    if(deviceStatus.getMusicInfo().getMusicPlayStatus().equals("play") && playingPos != -1){
                        if(result != null && result.size() > playingPos){
                            if(result.get(playingPos).getRawId().equals(deviceStatus.getMusicInfo().getRawId())){
                                result.get(playingPos).setMusicPlayStatus("play");
                                musicListAdapter.setCurrentPos(playingPos);
                            }
                        }
                    }
                }
                musicListAdapter.updateMusic(tempList);
                blMusic.setRefreshCompleted();
            } else {
                //TODO 这里不确定会不会取到错误数据 有新消息或者消息被删了  下标有变化 比如 以前是取10-20  新来了一条消息后 继续取10-20 其实取到的是以前的9-19
                //可能需要做去重和重定位
                musicListAdapter.addMusic(tempList);
                blMusic.setLoadingMoreCompleted();
            }
        }
        if (tempList == null || tempList.size() == 0) {
            if (musicListAdapter.getItemCount() == 0) {
                fl_message_container.setVisibility(View.GONE);
                llNoMusic.setVisibility(View.VISIBLE);
            } else {
                ToastUtil.showShort(MyApplication.get(), R.string.U_NoMoreRecords);
                blMusic.setLoadingMoreCompleted();
            }
        } else {
            fl_message_container.setVisibility(View.VISIBLE);
            LogUtils.i("getMessageList size--> : " + tempList.size());
            llNoMusic.setVisibility(View.GONE);
        }
    }
}
